package com.flying.pas.security.service;

import java.util.List;
import java.util.stream.Collectors;

import com.flying.framework.annotation.Param;
import com.flying.framework.annotation.Service;
import com.flying.framework.data.Data;
import com.flying.framework.security.Principal;
import com.flying.framework.service.AbstractService;
import com.flying.pas.security.AuthUser;
import com.flying.pas.security.model.Menu;

@Service("AuthService")
public class AuthService  extends AbstractService{
	private MenuService menuService;
	
	public void setMenuService(MenuService s) {
		this.menuService = s;
	}
	
	public Data auth(@Param(value="principal",required=true)Principal principal, 
			@Param(value="url",required=true)String url) throws Exception {
		AuthUser user = (AuthUser)principal;
		Menu menu = menuService.findByUrl(url);
		Long perm_id = menu.getPermId();
		if(menu.getMenuId() == null || perm_id == 0) 
			return new Data("authResult", true); //not protected url
		
		List<Long> perm_ids = user.getPerms().stream().map(x -> x.getPermId()).collect(Collectors.toList());
		return new Data("authResult", perm_ids.contains(perm_id) || true);
	}
}
